package com.yimu.lib.http.net;

import android.os.AsyncTask;
import android.text.TextUtils;


import com.yimu.lib.util.DESUtil;
import com.yimu.lib.util.MyLogger;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 描述：NetFuntion
 * 创建者：  Churck
 * 创建时间：16/9/22 16:07
 * 修改者： Churck
 * 修改时间：16/9/22 16:07
 * 版 本：v1.0
 */

public class NetFuntion {
    private String netwrodStr=null;
    private String url;
    private Map<String, String> data;
    private String method="POST";
    public NetFuntion(){
        super();
    }
    public void setUrl(String url) {
        this.url = url;
    }

    public void setData(Map<String, String> data) {
        this.data = data;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    protected NetFuntion(String url, Map<String, String> data, String method) {
        super();
        this.url = url;
        this.data = data;
        this.method = method;
    }
    protected String doRequestHttp(){
        if (method.equals("GET")){
           return doGetByHttpUrlConnection();
        }else {
            return doPostByHttpUrlConnection();
        }
    }


    /**
     * httpurlconnction 执行get请求
     *
     * @return
     */
    private String doGetByHttpUrlConnection() {
        String content = null;
        StringBuffer sb = new StringBuffer();
        sb.append("?");
        for (Map.Entry<String, String> entry : data.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        sb.deleteCharAt(sb.length() - 1);//删掉多余的？或者&
        try {
            URL url = new URL(this.url + sb.toString());
            MyLogger.i("网络请求路径 url:" + this.url + sb.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method);
            conn.setConnectTimeout(5000);//超时
            int statuCode = conn.getResponseCode();
            MyLogger.i("网络请求状态码 statuCode:" + statuCode);
            if (statuCode == 200) {
                //哈哈哈，请求成功了
                InputStream inputStream = conn.getInputStream();//从服务输入来的输入流
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer result = new StringBuffer();
                String result_str;
                while ((result_str = reader.readLine()) != null) {
                    result.append(result_str);
                }
                content = result.toString();
                MyLogger.d("======网络请求结果 sid:" + DESUtil.decrypt(data.get("sid"), "A3712C5D2F98263F8C9219E4DA604E2F"));
                MyLogger.d("======网络请求结果 result:" + result);
                return content;
            } else if (statuCode < 500 && statuCode > 400) {
                if (statuCode == 408) {
                    netwrodStr = "请求超时";
                } else {
                    netwrodStr = "请求错误";
                }
            } else if (statuCode >= 500) {
                if (statuCode == 500) {
                    netwrodStr = "服务器内部错误";
                } else if (statuCode == 503) {
                    netwrodStr = "服务不可用";
                } else if (statuCode == 503) {
                    netwrodStr = "读取数据超时";
                } else {
                    netwrodStr = "服务器错误";
                }
            }
        } catch (Exception e) {
            netwrodStr = "请求异常";
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 用httpurlconnection执行post请求
     *
     * @return
     */
    private String doPostByHttpUrlConnection() {
        String encoding = "UTF-8";
        String content = null;
        try {
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : data.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(URLEncoder.encode(entry.getValue(), "utf-8"));
                sb.append("&");
            }
            if (data != null & data.size() != 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            String params = sb.toString();
            byte[] entity = params.getBytes(encoding);
            MyLogger.i("网络请求路径 Url:" + url);
            URL url = new URL(this.url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(this.method);
            conn.setConnectTimeout(3*60*1000);
            conn.setReadTimeout(3*60*1000);
            conn.setDoOutput(true);//设置可以向服务器写数据
            conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(entity);//向服务器写数据
            int statuCode = conn.getResponseCode();
            MyLogger.d("======网络请求状态码 statuCode:" + statuCode);

            if (statuCode == 200) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer result = new StringBuffer();
                String result_str;
                while ((result_str = reader.readLine()) != null) {
                    result.append(result_str);
                }
                content = result.toString();
                MyLogger.d("======网络请求结果 sid:" + DESUtil.decrypt(data.get("sid"), "A3712C5D2F98263F8C9219E4DA604E2F"));
                MyLogger.d("======网络请求结果 result:" + result);
                return content;
            } else if (statuCode < 500 && statuCode > 400) {
                if (statuCode == 408) {
                    netwrodStr = "请求超时";
                } else {
                    netwrodStr = "请求错误";
                }
            } else if (statuCode >= 500) {
                if (statuCode == 500) {
                    netwrodStr = "服务器内部错误";
                } else if (statuCode == 503) {
                    netwrodStr = "服务不可用";
                } else if (statuCode == 504) {
                    netwrodStr = "读取数据超时";
                } else {
                    netwrodStr = "服务器错误";
                }
            }
        } catch (Exception e) {
            if (e instanceof SocketTimeoutException) {
                netwrodStr = "服务不可用!";
            } else {
                netwrodStr = "网络不给力,请换下网络!";
            }

            e.printStackTrace();
        }
        return null;
    }

    public String getNetwrodStr() {
        return netwrodStr;
    }
}
